home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / site / HTTP / Negotiate.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  12.9 KB  |  447 lines

  1.  
  2. package HTTP::Negotiate;
  3.  
  4. $VERSION = sprintf("%d.%02d", q$Revision: 1.6 $ =~ /(\d+)\.(\d+)/);
  5. sub Version { $VERSION; }
  6.  
  7. require 5.002;
  8. require Exporter;
  9. @ISA = qw(Exporter);
  10. @EXPORT = qw(choose);
  11.  
  12. require HTTP::Headers;
  13.  
  14. $DEBUG = 0;
  15.  
  16. sub choose ($;$)
  17. {
  18.     my($variants, $request) = @_;
  19.     my(%accept);
  20.  
  21.     unless (defined $request) {
  22.     $request = new HTTP::Headers;
  23.     $request->header('Accept', $ENV{HTTP_ACCEPT})
  24.       if $ENV{HTTP_ACCEPT};
  25.     $request->header('Accept-Charset', $ENV{HTTP_ACCEPT_CHARSET})
  26.       if $ENV{HTTP_ACCEPT_CHARSET};
  27.     $request->header('Accept-Encoding', $ENV{HTTP_ACCEPT_ENCODING})
  28.       if $ENV{HTTP_ACCEPT_ENCODING};
  29.     $request->header('Accept-Language', $ENV{HTTP_ACCEPT_LANGUAGE})
  30.       if $ENV{HTTP_ACCEPT_LANGUAGE};
  31.     }
  32.  
  33.  
  34.     $request->scan(sub {
  35.     my($key, $val) = @_;
  36.     return unless $key =~ s/^Accept-?//;
  37.     my $type = lc $key;
  38.     $type = "type" unless length $key;
  39.     $val =~ s/\s+//g;
  40.     my $name;
  41.     for $name (split(/,/, $val)) {
  42.         my(%param, $param);
  43.         if ($name =~ s/;(.*)//) {
  44.         for $param (split(/;/, $1)) {
  45.             my ($pk, $pv) = split(/=/, $param, 2);
  46.             $param{$pk} = $pv;
  47.         }
  48.         }
  49.         $name = lc $name;
  50.         if (defined $param{'q'}) {
  51.         $param{'q'} = 1 if $param{'q'} > 1;
  52.         $param{'q'} = 0 if $param{'q'} < 0;
  53.         } else {
  54.         $param{'q'} = 1;
  55.         }
  56.  
  57.         $param{'q'} = 1 unless defined $param{'q'};
  58.         $accept{$type}{$name} = \%param;
  59.     }
  60.     });
  61.  
  62.     my $any_lang = 0;
  63.     for $var (@$variants) {
  64.     if ($var->[5]) {
  65.         $any_lang = 1;
  66.         last;
  67.     }
  68.     }
  69.  
  70.     if ($DEBUG) {
  71.     print "Netgotiantion parameters in the request\n";
  72.     for $type (keys %accept) {
  73.         print " $type:\n";
  74.         for $name (keys %{$accept{$type}}) {
  75.         print "    $name\n";
  76.         for $pv (keys %{$accept{$type}{$name}}) {
  77.             print "      $pv = $accept{$type}{$name}{$pv}\n";
  78.         }
  79.         }
  80.     }
  81.     }
  82.  
  83.     my @Q = ();  # This is where we collect the results of the
  84.  
  85.     for (@$variants) {
  86.     my($id, $qs, $ct, $enc, $cs, $lang, $bs) = @$_;
  87.     $qs = 1 unless defined $qs;
  88.     $bs = 0 unless defined $bs;
  89.     if ($DEBUG) {
  90.         print "\nEvaluating $id ($ct)\n";
  91.         printf "  qs   = %.3f\n", $qs;
  92.         print  "  enc  = $enc\n"  if $enc && !ref($enc);
  93.         print  "  enc  = @$enc\n" if $enc && ref($enc);
  94.         print  "  cs   = $cs\n"   if $cs;
  95.         print  "  lang = $lang\n" if $lang;
  96.         print  "  bs   = $bs\n"   if $bs;
  97.     }
  98.  
  99.     my $qe = 1;
  100.     if (exists $accept{'encoding'} && $enc) {
  101.         my @enc = ref($enc) ? @$enc : ($enc);
  102.         for (@enc) {
  103.         print "Is encoding $_ accepted? " if $DEBUG;
  104.         unless(exists $accept{'encoding'}{$_}) {
  105.             print "no\n" if $DEBUG;
  106.             $qe = 0;
  107.             last;
  108.         } else {
  109.             print "yes\n" if $DEBUG;
  110.         }
  111.         }
  112.     }
  113.  
  114.     my $qc  = 1;
  115.     if (exists $accept{'charset'} && $cs && $cs ne 'us-ascii' ) {
  116.         $qc = 0 unless $accept{'charset'}{$cs};
  117.     }
  118.  
  119.     my $ql  = 1;
  120.     if ($lang && exists $accept{'language'}) {
  121.         my @lang = ref($lang) ? @$lang : ($lang);
  122.         my $q = undef;
  123.         for (@lang) {
  124.         next unless exists $accept{'language'}{$_};
  125.         my $this_q = $accept{'language'}{$_}{'q'};
  126.         $q = $this_q unless defined $q;
  127.         $q = $this_q if $this_q > $q;
  128.         }
  129.         unless (defined $q) {
  130.         my $selected = undef;
  131.         for $al (keys %{ $accept{'language'} }) {
  132.             if (substr($lang, 0, length($al)) eq $al) {
  133.             $selected = $al unless defined $selected;
  134.             $selected = $al if length($al) > length($selected);
  135.             }
  136.         }
  137.         $q = $accept{'language'}{$selected}{'q'} if $selected;
  138.  
  139.         $q = 0.001 unless defined $q;
  140.         }
  141.         $ql = $q;
  142.     } else {
  143.         $ql = 0.5 if $any_lang && exists $accept{'language'};
  144.     }
  145.  
  146.     my $q   = 1;
  147.     my $mbx = undef;
  148.     if (exists $accept{'type'} && $ct) {
  149.         $ct =~ s/\s+//g;
  150.         my $params = "";
  151.         $params = $1 if $ct =~ s/;(.*)//;
  152.         my($type, $subtype) = split("/", $ct, 2);
  153.         my %param = ();
  154.         for $param (split(/;/, $params)) {
  155.         my($pk,$pv) = split(/=/, $param, 2);
  156.         $param{$pk} = $pv;
  157.         }
  158.  
  159.         my $sel_q = undef;
  160.         my $sel_mbx = undef;
  161.         my $sel_specificness = 0;
  162.  
  163.         ACCEPT_TYPE:
  164.         for $at (keys %{ $accept{'type'} }) {
  165.         print "Consider $at...\n" if $DEBUG;
  166.         my($at_type, $at_subtype) = split("/", $at, 2);
  167.         next if $at_type    ne '*' && $at_type    ne $type;
  168.         next if $at_subtype ne '*' && $at_subtype ne $subtype;
  169.         my $specificness = 0;
  170.         $specificness++ if $at_type ne '*';
  171.         $specificness++ if $at_subtype ne '*';
  172.         while (($pk, $pv) = each %param) {
  173.             print "Check if $pk = $pv is true\n" if $DEBUG;
  174.             next unless exists $accept{'type'}{$at}{$pk};
  175.             next ACCEPT_TYPE
  176.               unless $accept{'type'}{$at}{$pk} eq $pv;
  177.             print "yes it is!!\n" if $DEBUG;
  178.             $specificness++;
  179.         }
  180.         print "Hurray, type match with specificness = $specificness\n"
  181.           if $DEBUG;
  182.  
  183.         if (!defined($sel_q) || $sel_specificness < $specificness) {
  184.             $sel_q   = $accept{'type'}{$at}{'q'};
  185.             $sel_mbx = $accept{'type'}{$at}{'mbx'};
  186.             $sel_specificness = $specificness;
  187.         }
  188.         }
  189.         $q   = $sel_q || 0;
  190.         $mbx = $sel_mbx;
  191.     }
  192.  
  193.     my $Q;
  194.     if (!defined($mbx) || $mbx >= $bs) {
  195.         $Q = $qs * $qe * $qc * $ql * $q;
  196.     } else {
  197.         $Q = 0;
  198.         print "Variant's size is too large ==> Q=0\n" if $DEBUG;
  199.     }
  200.  
  201.     if ($DEBUG) {
  202.         $mbx = "undef" unless defined $mbx;
  203.         printf "Q=%.3f", $Q;
  204.         print "  (q=$q, mbx=$mbx, qe=$qe, qc=$qc, ql=$ql, qs=$qs)\n";
  205.     }
  206.  
  207.     push(@Q, [$id, $Q, $bs]);
  208.     }
  209.  
  210.  
  211.     @Q = sort { $b->[1] <=> $a->[1] || $a->[2] <=> $b->[2] } @Q;
  212.  
  213.     return @Q if wantarray;
  214.     return undef unless @Q;
  215.     return undef if $Q[0][1] == 0;
  216.     $Q[0][0];
  217. }
  218.  
  219. 1;
  220.  
  221. __END__
  222.  
  223.  
  224. =head1 NAME
  225.  
  226. choose - choose a variant of a document to serve (HTTP content negotiation)
  227.  
  228. =head1 SYNOPSIS
  229.  
  230.  use HTTP::Negotiate;
  231.  
  232.  $variants =
  233.   [['var1',  1.000, 'text/html',   undef,   'iso-8859-1',   'en',   3000],
  234.    ['var2',  0.950, 'text/plain',  'gzip',  'us-ascii',     'no',    400],
  235.    ['var3',  0.3,   'image/gif',   undef,   undef,          undef, 43555],
  236.   ];
  237.  
  238.  @prefered = choose($variants, $request_headers);
  239.  $the_one  = choose($variants);
  240.  
  241. =head1 DESCRIPTION
  242.  
  243. This module provide a complete implementation of the HTTP content
  244. negotiation algorithm specified in F<draft-ietf-http-v11-spec-00.ps>
  245. chapter 12.  Content negotiation allows for the selection of a
  246. preferred content representation based upon attributes of the
  247. negotiable variants and the value of the various Accept* header fields
  248. in the request.
  249.  
  250. The variants are ordered by preference by calling the function
  251. choose().
  252.  
  253. The first parameter is a description of the variants that we can
  254. choose among.  The variants are described by a reference to an array.
  255. Each element in this array is an array with the values [$id, $qs,
  256. $content_type, $content_encoding, $charset, $content_language,
  257. $content_length].  The meaning of these values are described
  258. below. The $content_encoding and $content_language can be either a
  259. single scalar value or an array reference if there are several values.
  260.  
  261. The second optional parameter is a reference to the request headers.
  262. This is used to look for "Accept*" headers.  You can pass a reference
  263. to either a HTTP::Request or a HTTP::Headers object.  If this
  264. parameter is missing, then the accept specification is initialized
  265. from the CGI environment variables HTTP_ACCEPT, HTTP_ACCEPT_CHARSET,
  266. HTTP_ACCEPT_ENCODING and HTTP_ACCEPT_LANGUAGE.
  267.  
  268. In array context, choose() returns a list of variant
  269. identifier/calculated quality pairs.  The values are sorted by
  270. quality, highest quality first.  If the calculated quality is the same
  271. for two variants, then they are sorted by size (smallest first). I<E.g.>:
  272.  
  273.   (['var1' => 1], ['var2', 0.3], ['var3' => 0]);
  274.  
  275. Note that also zero quality variants are included in the return list
  276. even if these should never be served to the client.
  277.  
  278. In scalar context, it returns the identifier of the variant with the
  279. highest score or C<undef> if none have non-zero quality.
  280.  
  281. If the $HTTP::Negotiate::DEBUG variable is set to TRUE, then a lot of
  282. noise is generated on STDOUT during evaluation of choose().
  283.  
  284. =head1 VARIANTS
  285.  
  286. A variant is described by a list of the following values.  If the
  287. attribute does not make sense or is unknown for a variant, then use
  288. C<undef> instead.
  289.  
  290. =over 3
  291.  
  292. =item identifier
  293.  
  294. This is just some string that you use as a name for the variant.  The
  295. identifier of the preferred variant is returned by choose().
  296.  
  297. =item qs
  298.  
  299. This is a number between 0.000 and 1.000 that describes the "source
  300. quality".  This is what F<draft-ietf-http-v11-spec-00.ps> says about this
  301. value:
  302.  
  303. Source quality is measured by the content provider as representing the
  304. amount of degradation from the original source.  For example, a
  305. picture in JPEG form would have a lower qs when translated to the XBM
  306. format, and much lower qs when translated to an ASCII-art
  307. representation.  Note, however, that this is a function of the source
  308. - an original piece of ASCII-art may degrade in quality if it is
  309. captured in JPEG form.  The qs values should be assigned to each
  310. variant by the content provider; if no qs value has been assigned, the
  311. default is generally "qs=1".
  312.  
  313. =item content-type
  314.  
  315. This is the media type of the variant.  The media type does not
  316. include a charset attribute, but might contain other parameters.
  317. Examples are:
  318.  
  319.   text/html
  320.   text/html;version=2.0
  321.   text/plain
  322.   image/gif
  323.   image/jpg
  324.  
  325. =item content-encoding
  326.  
  327. This is one or more content encodings that has been applied to the
  328. variant.  The content encoding is generally used as a modifier to the
  329. content media type.  The most common content encodings are:
  330.  
  331.   gzip
  332.   compress
  333.  
  334. =item content-charset
  335.  
  336. This is the character set used when the variant contains textual
  337. content.  The charset value should generally be C<undef> or one of these:
  338.  
  339.   us-ascii
  340.   iso-8859-1 ... iso-8859-9
  341.   iso-2022-jp
  342.   iso-2022-jp-2
  343.   iso-2022-kr
  344.   unicode-1-1
  345.   unicode-1-1-utf-7
  346.   unicode-1-1-utf-8
  347.  
  348. =item content-language
  349.  
  350. This describes one or more languages that are used in the variant.
  351. Language is described like this in F<draft-ietf-http-v11-spec-00.ps>: A
  352. language is in this context a natural language spoken, written, or
  353. otherwise conveyed by human beings for communication of information to
  354. other human beings.  Computer languages are explicitly excluded.
  355.  
  356. The language tags are the same as those defined by RFC-1766.  Examples
  357. are:
  358.  
  359.   no               Norwegian
  360.   en               International English
  361.   en-US            US English
  362.   en-cockney
  363.  
  364. =item content-length
  365.  
  366. This is the number of bytes used to represent the content.
  367.  
  368. =back
  369.  
  370. =head1 ACCEPT HEADERS
  371.  
  372. The following Accept* headers can be used for describing content
  373. preferences in a request (This description is an edited extract from
  374. F<draft-ietf-http-v11-spec-00.ps>):
  375.  
  376. =over 3
  377.  
  378. =item Accept
  379.  
  380. This header can be used to indicate a list of media ranges which are
  381. acceptable as a reponse to the request.  The "*" character is used to
  382. group media types into ranges, with "*/*" indicating all media types
  383. and "type/*" indicating all subtypes of that type.
  384.  
  385. The parameter q is used to indicate the quality factor, which
  386. represents the user's preference for that range of media types.  The
  387. parameter mbx gives the maximum acceptable size of the response
  388. content. The default values are: q=1 and mbx=infinity. If no Accept
  389. header is present, then the client accepts all media types with q=1.
  390.  
  391. For example:
  392.  
  393.   Accept: audio/*;q=0.2;mbx=200000, audio/basic
  394.  
  395. would mean: "I prefer audio/basic (of any size), but send me any audio
  396. type if it is the best available after an 80% mark-down in quality and
  397. its size is less than 200000 bytes"
  398.  
  399.  
  400. =item Accept-Charset
  401.  
  402. Used to indicate what character sets are acceptable for the response.
  403. The "us-ascii" character set is assumed to be acceptable for all user
  404. agents.  If no Accept-Charset field is given, the default is that any
  405. charset is acceptable.  Example:
  406.  
  407.   Accept-Charset: iso-8859-1, unicode-1-1
  408.  
  409.  
  410. =item Accept-Encoding
  411.  
  412. Restricts the Content-Encoding values which are acceptable in the
  413. response.  If no Accept-Encoding field is present, the server may
  414. assume that the client will accept any content encoding.  An empty
  415. Accept-Encoding means that no content encoding is acceptable.  Example:
  416.  
  417.   Accept-Encoding: compress, gzip
  418.  
  419.  
  420. =item Accept-Language
  421.  
  422. This field is similar to Accept, but restrict the set of natural
  423. languages that are preferred as a response.  Each language may be
  424. given an associated quality value which represents an estimate of the
  425. user's comprehension of that language.  For example:
  426.  
  427.   Accept-Language: no, en-gb;q=0.8, de;q=0.55
  428.  
  429. would mean: "I prefer Norwegian, but will accept British English (with
  430. 80% comprehension) or German (with 55% comprehension).
  431.  
  432. =back
  433.  
  434.  
  435. =head1 COPYRIGHT
  436.  
  437. Copyright 1996, Gisle Aas.
  438.  
  439. This library is free software; you can redistribute it and/or
  440. modify it under the same terms as Perl itself.
  441.  
  442. =head1 AUTHOR
  443.  
  444. Gisle Aas <aas@sn.no>
  445.  
  446. =cut
  447.